package com.vincent.seeyou.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;


import com.vincent.seeyou.R;
import com.vincent.seeyou.SYMessageReceiver;
import com.vincent.seeyou.adapter.MessageChatAdapter;
import com.vincent.seeyou.util.CommonUtils;

import java.util.List;

import cn.bmob.im.BmobChatManager;
import cn.bmob.im.BmobNotifyManager;
import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.db.BmobDB;
import cn.bmob.im.inteface.EventListener;
import cn.bmob.im.util.BmobLog;

public class ChatActivity extends BaseAndCheckInActivity implements EventListener {

    private EditText editText_message;
    private ListView listView_message;
    MessageChatAdapter mAdapter;

    private static int MsgPagerNum;
    private BmobChatUser targetUser;
    private String targetId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        bmobChatManager = BmobChatManager.getInstance(this);
        MsgPagerNum = 0;

        targetUser = (BmobChatUser) getIntent().getSerializableExtra("user");
        targetId = targetUser.getObjectId();
        BmobLog.i("聊天对象：" + targetUser.getUsername() + ",targetId = "
                + targetId);
        initView();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // 新消息到达，重新刷新界面
        initOrRefresh();
        SYMessageReceiver.ehList.add(this);// 监听推送的消息
        // 有可能锁屏期间，在聊天界面出现通知栏，这时候需要清除通知和清空未读消息数
        BmobNotifyManager.getInstance(this).cancelNotify();
        BmobDB.create(this).resetUnread(targetId);
        //清空消息未读数-这个要在刷新之后
        SYMessageReceiver.mNewNum=0;
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        SYMessageReceiver.ehList.remove(this);// 监听推送的消息


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chat, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView(){
        editText_message = (EditText)findViewById(R.id.editText_message);
        listView_message= (ListView)findViewById(R.id.listView_message);
        initListView();
    }
    private void initListView(){
        listView_message.setDividerHeight(0);
        initOrRefresh();
        listView_message.setSelection(mAdapter.getCount() - 1);
    }

    private void initOrRefresh() {
        if (mAdapter != null) {
            if (SYMessageReceiver.mNewNum != 0) {// 用于更新当在聊天界面锁屏期间来了消息，这时再回到聊天页面的时候需要显示新来的消息
                int news=  SYMessageReceiver.mNewNum;//有可能锁屏期间，来了N条消息,因此需要倒叙显示在界面上
                int size = initMsgData().size();
                for(int i=(news-1);i>=0;i--){
                    mAdapter.add(initMsgData().get(size-(i+1)));// 添加最后一条消息到界面显示
                }
                listView_message.setSelection(mAdapter.getCount() - 1);
            } else {
                mAdapter.notifyDataSetChanged();
            }
        } else {
            mAdapter = new MessageChatAdapter(this, initMsgData());
            listView_message.setAdapter(mAdapter);
        }
    }
    /**
     * 加载消息历史，从数据库中读出
     */
    private List<BmobMsg> initMsgData() {
        List<BmobMsg> list = BmobDB.create(this).queryMessages(targetId,
                MsgPagerNum);
        return list;
    }

    private void refreshMessage(BmobMsg msg) {
        // 更新界面
        mAdapter.add(msg);
        listView_message.setSelection(mAdapter.getCount() - 1);
        editText_message.setText("");
    }


    public void onSend(View view){

        final String msg = editText_message.getText().toString();
        if (msg.equals("")) {
            ShowToast("请输入发送消息!");
            return;
        }
        boolean isNetConnected = CommonUtils.isNetworkAvailable(this);
        if (!isNetConnected) {
            ShowToast(R.string.tip_network);
            // return;
        }
        // 组装BmobMessage对象
        BmobMsg message = BmobMsg.createTextSendMsg(this, targetId, msg);
        // 默认发送完成，将数据保存到本地消息表和最近会话表中
        bmobChatManager.sendTextMessage(targetUser, message);
        // 刷新界面
        refreshMessage(message);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == NEW_MESSAGE) {
                BmobMsg message = (BmobMsg) msg.obj;
                String uid = message.getBelongId();
                if (!uid.equals(targetId))// 如果不是当前正在聊天对象的消息，不处理
                    return;
                mAdapter.add(message);
                // 在聊天页面收到的消息均是已读状态
                message.setIsReaded(BmobConfig.STATE_READED);
                // 保存接收到的消息-并发送已读回执给对方
                BmobChatManager.getInstance(ChatActivity.this)
                        .saveReceiveMessage(true, message);
                // 定位
                listView_message.setSelection(mAdapter.getCount() - 1);
            }
        }
    };

    public static final int NEW_MESSAGE = 0x001;// 收到消息

    @Override
    public void onMessage(BmobMsg bmobMsg) {
        Message handlerMsg = handler.obtainMessage(NEW_MESSAGE);
        handlerMsg.obj = bmobMsg;
        handler.sendMessage(handlerMsg);
    }

    @Override
    public void onReaded(String conversionId, String msgTime) {

        // 此处应该过滤掉不是和当前用户的聊天的回执消息界面的刷新
        if (conversionId.split("&")[1].equals(targetId)) {
            // 修改界面上指定消息的阅读状态
            for (BmobMsg msg : mAdapter.getList()) {
                if (msg.getConversationId().equals(conversionId)
                        && msg.getMsgTime().equals(msgTime)) {
                    msg.setStatus(BmobConfig.STATUS_SEND_RECEIVERED);
                }
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onNetChange(boolean isNetConnected) {
        if (!isNetConnected) {
            ShowToast(R.string.tip_network);
        }
    }

    @Override
    public void onAddUser(BmobInvitation bmobInvitation) {

    }

    @Override
    public void onOffline() {
//        showOfflineDialog(this);
    }
}
